import { useXAgent, useXChat, Sender, Bubble, Suggestion } from '@ant-design/x';
import { Flex, GetProp, Typography } from 'antd';
import OpenAI from 'openai';
import React, { useState } from 'react';
import { UserOutlined } from '@ant-design/icons';
import markdownit from 'markdown-it';

const client = new OpenAI({
    apiKey: 'sk-ef8d6eea58ba4318a19399ea3e0d08c3',
    baseURL: 'https://api.deepseek.com',
    dangerouslyAllowBrowser: true,
});

const md = markdownit({
    html: true,
    breaks: true,
});

const roles: GetProp<typeof Bubble.List, 'roles'> = {
    ai: {
        placement: 'start',
        avatar: { icon: <UserOutlined />, style: { background: '#fde3cf' } },
        typing: { step: 5, interval: 20 },
        style: {
            maxWidth: 700,
        },
    },
    local: {
        placement: 'end',
        avatar: { icon: <UserOutlined />, style: { background: '#87d068' } },
    },
};

const renderMarkdown = (content: string) => (
    <Typography>
        {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
        <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
    </Typography>
);

let mockSuccess = false;

const ChatWindow: React.FC = () => {
    const [value, setValue] = useState('');

    const [agent] = useXAgent({
        request: async (info, callbacks) => {
            console.log("info>>> ", info);
            const { messages, message } = info;

            const { onSuccess, onUpdate, onError } = callbacks;

            console.log("messages --> ", messages, "message --> ", message);

            // 清空输入框
            setValue('');

            let content: string = '';
            try {
                const stream = await client.chat.completions.create({
                    model: 'deepseek-reasoner',
                    messages: [{ role: 'user', content: message || '' }],
                    stream: true,
                });

                // 流失更新
                for await (const chunk of stream) {
                    content += chunk.choices[0]?.delta?.content || '';
                    onUpdate(content);
                }

                if (mockSuccess) {
                    onSuccess(content);
                }

            } catch (error) {
                console.log('程序报错 >>> ', error);
                onError(new Error('Mock request failed'));
            }
        },
    });

    const {
        onRequest,
        messages,
    } = useXChat({
        agent,
        requestPlaceholder: 'Waiting...',
        requestFallback: 'Mock failed return. Please try again later.',
    });

    return (
        <Flex vertical style={{ flex: 1, }} gap="middle">
            <Bubble.List
                roles={roles}
                style={{ height: '80vh' }}
                items={messages.map(({ id, message, status }) => ({
                    key: id,
                    role: status === 'local' ? 'local' : 'ai',
                    content: renderMarkdown(message),
                }))}
            />

            <Suggestion
                items={[{ label: 'Write a report', value: 'report' }]}
            >
                {({ onTrigger, onKeyDown }) => (
                    <>
                        <Sender
                            loading={agent.isRequesting()}
                            value={value}
                            onChange={(nextVal) => {
                                if (nextVal === '/') {
                                    onTrigger();
                                } else if (!nextVal) {
                                    onTrigger(false);
                                }
                                setValue(nextVal);
                            }}
                            onSubmit={onRequest}
                            onKeyDown={onKeyDown}
                            placeholder='Type "/" to trigger suggestion'
                        />
                    </>
                )}
            </Suggestion>
        </Flex>
    );
};

export default ChatWindow;